package com.youlu.campus.web.user.controller;


import com.google.common.collect.Lists;
import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.base.interactive.vo.ActivitySignUpRequest;
import com.youlu.campus.entity.*;
import com.youlu.campus.entity.VO.req.CheckMobileVO;
import com.youlu.campus.entity.VO.req.CreatedUserInfoExtendCommand;
import com.youlu.campus.service.activity.ActivityService;
import com.youlu.campus.service.activity.UserParticipateActivityInfoService;
import com.youlu.campus.service.feed.ActivityFeedInfoService;
import com.youlu.campus.service.platform.PointPlatformConfigService;
import com.youlu.campus.service.qq.QQMiniUserService;
import com.youlu.campus.service.ranking.UserPointRankingService;
import com.youlu.campus.service.visitor.UserInfoExtendService;
import com.youlu.campus.service.visitor.UserPointsService;
import com.youlu.campus.web.common.base.RequestContext;
import com.youlu.campus.web.user.service.UserService;
import com.yuelin.infrastructure.quantum.common.QResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Objects;

@Slf4j
@RestController
public class UserInfoExtendController {

    @Autowired
    private UserService userService;
    @Autowired
    private QQMiniUserService qqMiniUserService;

    @Autowired
    private UserInfoExtendService userInfoExtendService;
    @Autowired
    private ActivityService activityService;
    @Autowired
    private ActivityFeedInfoService activityFeedInfoService;
    @Autowired
    private PointPlatformConfigService pointPlatformConfigService;
    @Autowired
    private UserPointsService userPointsService;
    @Autowired
    private UserPointRankingService userPointRankingService;
    @Autowired
    private UserParticipateActivityInfoService upService;


    public static void main(String[] args) {
        String a = "";
        String b = "";
        String c = "";
        String d = "";
        String e = "";
        String[] params = new String[]{a, b, c, d, e};
        System.out.println(StringUtils.isAllBlank(params));


    }

    @PostMapping("/mini-app/userinfo/add/ext")
    public QResult userInfoExtendAdd(@RequestBody @Validated CreatedUserInfoExtendCommand command,
                                     BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return QResult.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        this.checkUserInfo(command);
        this.commonUserInfoAddExt(command);
        return QResult.success(null);
    }

    /**
     * 用户未参加活动，报名参加活动
     *
     * @param command
     * @param bindingResult
     * @return
     */
    @PostMapping("/mini-app/plus/userinfo/add")
    public QResult plusUserInfoExtendAdd(@RequestBody @Validated CreatedUserInfoExtendCommand command,
                                         BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return QResult.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        // 1、老业务 2、新业务
        command.setType(2);
        this.commonUserInfoAddExt(command);
        return QResult.success(null);
    }


    private void commonUserInfoAddExt(CreatedUserInfoExtendCommand command) {
        if (command.getMustCode()) {
            CheckMobileVO req = new CheckMobileVO();
            req.setUserPO(RequestContext.getCurUser());
            req.setCode(command.getCode());
            req.setPaltform(RequestContext.getCurPlatform());
            req.setMobile(command.getMobile());
            boolean re = userService.checkMobile(req);
            if (!re) {
                log.error("用户验证码错误:{}", command.getCode());
                throw new BusinessException("验证码错误");
            }
        }
        // 标记账号的手机号被验证
        UserPO userPO = new UserPO();
        userPO.setId(RequestContext.getCurUser().getId());
        userPO.setMobile(command.getMobile());
        userPO.setCheckedMobile(true);
        userPO.setBinded(null);
        userPO.setCheckedMobileTime(new Date());
        userService.updateUserInfo(userPO);
        command.setCurrentUser(RequestContext.getCurUser());
        userInfoExtendService.addUserInfoExt(command);
        if (!"wechat-mini".equals(RequestContext.getCurPlatform())) {
            QQMiniUserPO qqMiniUserPO = new QQMiniUserPO();
            qqMiniUserPO.setAccountInfoId(RequestContext.getUserId());
            qqMiniUserPO.setMobile(command.getMobile());
            qqMiniUserPO.setCheckedMobile(true);
            qqMiniUserPO.setBinded(null);
            qqMiniUserPO.setCheckedMobileTime(new Date());
            qqMiniUserService.updateQQMiniUserPO(qqMiniUserPO);
        }
        //微信小程序平台不需要报名去更新邀请
        String activityId = command.getActivityId();
        ActivityInfo activityInfo = activityService.findOne(activityId);
        //小程序宣传类新用户邀请更新
        if (Objects.nonNull(activityInfo) && Lists.newArrayList("publicity","continuous-daka").contains(activityInfo.getType())) {
            ActivitySignUpRequest request = new ActivitySignUpRequest();
            request.setActivityId(command.getActivityId());
            request.setPlatform(RequestContext.getCurPlatform());
            request.setAppId(RequestContext.getAppId());
            request.setUserId(RequestContext.getUserId());
            activityService.extSignUpActivity(request, RequestContext.getCurUser());
        }
        // 添加Feed流
        ActivityFeedInfo feedInfo = new ActivityFeedInfo();
        feedInfo.setActivityId(command.getActivityId());
        feedInfo.setActivityStatus(2);
        feedInfo.setStatus(true);
        feedInfo.setImageUr(RequestContext.getCurUser().getAvatarUrl());
        feedInfo.setContent(RequestContext.getCurUser().getNickName() + "报名活动");
        activityFeedInfoService.addActivityFeedInfo(command.getActivityId(), 2, feedInfo);
        activityService.updateActivityJoinNum(command.getActivityId(), 1, new Date());
        upService.increJoinedCount(command.getActivityId(), 1L);
    }

    @GetMapping("/mini-app/userinfo/query/ext")
    public QResult userInfoExtendQuery() {
        return QResult.success(userInfoExtendService.findUserInfoByUserId(RequestContext.getCurUser()));
    }

    @PostMapping("/mini-app/plus/userinfo/update")
    public QResult updateUserInfo(@RequestBody UserInfoExtend userInfoExtend) {
        checkUpdateInfo(userInfoExtend);
        this.userInfoExtendService.updateByUserId(RequestContext.getCurUser(), userInfoExtend);
        return QResult.success(null);
    }

    @GetMapping("/mini-app/userinfo/query")
    public QResult getUserInfoByActivityId(@RequestParam("activityId") String activityId) {
        return QResult.success(userInfoExtendService.getUserInfoByActivityId(activityId, RequestContext.getCurUser()));
    }

    private void checkUpdateInfo(UserInfoExtend userInfoExtend) {
        String name = userInfoExtend.getName();
        String universityId = userInfoExtend.getUniversityId();
        String universityName = userInfoExtend.getUniversityName();
        String grade = userInfoExtend.getGrade();
        String majorId = userInfoExtend.getMajorId();
        String majorName = userInfoExtend.getMajorName();
        String[] params = new String[]{name, universityId, universityName, grade, majorId, majorName};
        if (StringUtils.isAllBlank(params)) {
            log.error("修改用户信息参数错误");
            throw new BusinessException("参数错误");
        }
    }

    private void checkUserInfo(CreatedUserInfoExtendCommand command) {
        if (StringUtils.isBlank(command.getGrade())) {
            throw new BusinessException("年级必填");
        }
        if (StringUtils.isBlank(command.getActivityId())) {
            throw new BusinessException("活动ID必填");
        }
        if (StringUtils.isBlank(command.getCaLevel())) {
            throw new BusinessException("证书等级必填");
        }
        if (StringUtils.isBlank(command.getCaType())) {
            throw new BusinessException("证书类型必填");
        }
    }


}
